
package com.et114.core.control;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/*
 * @author guanhw
 */
public final class Container {
	public static final int	UNKNOWN			= 0;
	public static final int	TOMCAT			= 1;
	public static final int	RESIN			= 2;
	public static final int	ORION			= 3;	// Orion or OC4J
	public static final int	WEBLOGIC		= 4;
	public static final int	HPAS			= 5;
	public static final int	JRUN			= 6;
	public static final int	WEBSPHERE		= 7;
	
	private static int		result			= - 1;
	private static Map		classMappings	= null;

    static {
		classMappings = new HashMap ( 6 );
		classMappings.put ( "org.apache.jasper.runtime.JspFactoryImpl" ,	new Integer ( TOMCAT ) );
		classMappings.put ( "com.caucho.jsp.JspServlet" , new Integer ( RESIN ) );
		classMappings.put ( "com.evermind.server.http.JSPServlet" ,new Integer ( ORION ) );
		classMappings.put ( "weblogic.servlet.JSPServlet" , new Integer (WEBLOGIC ) );
		classMappings.put ( "com.hp.mwlabs.j2ee.containers.servlet.jsp.JspServlet" ,	new Integer ( HPAS ) );
		classMappings.put ( "jrun.servlet.WebApplicationService" , new Integer (	JRUN ) );
		classMappings.put ( "com.ibm.ws.webcontainer.jsp.servlet.JspServlet" ,	new Integer ( WEBSPHERE ) );
    }

    public static int get() {
		if ( result == - 1 ) {
			final String classMatch = searchForClosestClass ( classMappings );
			
			if ( classMatch == null ) {
				result = UNKNOWN;
			} else {
				result = ( ( Integer ) classMappings.get ( classMatch ) )
						.intValue ( );
			}
		}
		return result;
	}

	
	private static String searchForClosestClass ( Map classMappings ) {
		ClassLoader loader = Container.class.getClassLoader ( );
		while (loader != null) {
			for ( Iterator iterator = classMappings.keySet ( ).iterator ( ) ; iterator
					.hasNext ( ) ; ) {
				String className = ( String ) iterator.next ( );
				
				try {
					loader.loadClass ( className );
					return className;
				} catch ( ClassNotFoundException e ) {
				}
			}
			loader = loader.getParent ( );
		}
		return null;
	}
}
